from pyecharts.charts import Bar, Timeline
from pyecharts.globals import ThemeType
from pyecharts.options import LabelOpts, TitleOpts


def bar_chart(year, data):
    bar = Bar()
    x_data = []
    y_data = []
    data.reverse()
    for i in data:
        x_data.append(i[0])
        y_data.append(i[1] / 100000000)
    bar.add_xaxis(x_data)
    bar.add_yaxis("GDP(亿)", y_data, label_opts=LabelOpts(position="right"))
    bar.reversal_axis()
    bar.set_global_opts(title_opts=TitleOpts(title=f"{year}年全球前8名GDP排行"))
    return bar


f = open("1960-2019全球GDP数据.csv", "r", encoding="utf-8")
gdp_data = f.readlines()
f.close()
gdp_data.pop(0)
data = {}
for line in gdp_data:
    line_data = line.split(",")
    year = int(line_data[0])
    country = line_data[1]
    gdp = float(line_data[2])
    try:
        data[year].append([country, gdp])
    except KeyError:
        data[year] = []
        data[year].append([country, gdp])

time_line = Timeline({"theme": ThemeType.LIGHT})
year_list = sorted(data.keys())
for year in year_list:
    data[year].sort(key=lambda x: x[1], reverse=True)
    time_line.add(bar_chart(year, data[year][0:8]), str(year))

time_line.add_schema(
    is_auto_play=True,
    play_interval=1000,
    is_loop_play=False,
    is_timeline_show=True
)

time_line.render("gdp.html")
